// pages/order/order.js
import Big from 'big.js'
const request = require('@/utils/request.js')
const constants = require('@/utils/khyConstants.js')

Page({

  /**
   * 页面的初始数据
   */
  data: {
    inputJi: true,
    inputShou: true,
    jiAddressId: null,
    shouAddressId: null,
    orderType: '1',//订单类型：1大众下单；2理货员下单
    orderInfo: {
      goodsType: '4',//物品类型
      insureStatus: '0',//是否保价
      declarationValue: '',//声明价值
      insureValue: '',//保价金额
      packageState: '0',//快递状态_已下单
      payState: '0',//付款状态_未付款
      startStation: '',
      startStationName: '',
      senderName: '',
      senderPhone: '',
      endStation: '',
      endStationName: '',
      consigneeName: '',
      consigneePhone: '',
      goodsName: '',
      goodsWeight: '',
      goodsLong: '',
      goodsWidth: '',
      goodsHeight: '',
      payMode: '',
      goodsPhoto:"",
      discountValue: 0,//优惠金额
      couponId: '',//优惠卷id
      couponName: '',//优惠卷名称
    },
    excludeList: {
      goodsWeight: 'goodsWeight',
      goodsLong: 'goodsLong',
      goodsWidth: 'goodsWidth',
      goodsHeight: 'goodsHeight',

    },
    requireList: {
      goodsType: '请选择物品类型',
      insureStatus: '请选择是否保价',
      senderPhone: '请录入寄件信息',
      consigneePhone: '请录入收件信息',
      goodsName: '请录入物品信息',
      //goodsWeight: '物品重量',
      //goodsLong: '物品长',
      //goodsWidth: '物品宽',
      //goodsHeight: '物品高',
      goodsPhoto: '物品照片',
      payMode: '付款方式',
    },
    payModeName: '',
    goodsTypeName: '',
    insureStatusName: '',
    goodsTypeVisible: false,
    insureStatusVisible: false,
    payModeVisible: false,
    couponNameVisible: false,
    insureStatusList: getApp().globalData.dictData['insureStatus'],
    isDiscountList: getApp().globalData.dictData['isDiscount'],//是否使用新人注册优惠
    goodsTypeList: getApp().globalData.dictData['goodsType'],
    payModeList: getApp().globalData.dictData['payMode'],
    basePrice: getApp().globalData.basePrice, //预估底价
    imgList:[],// 上传的图片
    isCal: false, //根据商品类型，其他类型需要计算预估价格
    insureRate: getApp().globalData.insureRate,//保价费用比例
    isNew: 0,//是否是注册新人
    isDiscount: '',
    isDiscountName: '',
    isDiscountVisible: false,
    discountDefaultValue: 0,
    loading: false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    const app = getApp();
    this.setData({
      orderType: getApp().globalData.pageData[constants.page_order]['orderType'],
      order_bg:app.globalData.nginxIp+'/img/order_bg.png',
      order_bg_text:app.globalData.nginxIp+'/img/order_bg_text.png',
      sctp_img:app.globalData.nginxIp+'/img/sctp.png',
      
    })
    this.getDictData()

    //清理优惠卷
    getApp().globalData.pageData[constants.page_couponSelect] = {}

    // if (getApp().globalData.pageData[constants.page_order]['orderType'] == '1') {
    //   //大众登录，需要查询用户信息，查看是否使用新人优惠
    //   this.getKhyUser()
    // } else {
    //   this.setData({
    //     isNew: '0'
    //   })
    // }
    //this.getParamInfo()
  },

  // getKhyUser() {
  //   let user = getApp().getUserInfo()
  //   request.get('/HomeController/getKhyUser', {userNo: user.userNo}).then(res => {
  //     if (res.data.code == constants.resultSuccessCode
  //       && res.data.result) {
  //         console.log(res)
  //         if (res.data.result.isNew == '1') {
  //           this.setData({
  //             isNew: '1'
  //           })
  //         }
  //     }
  //   })
  // },

  getDictData() {
    let dictString = constants.dict.优惠金额
    request.get('/HomeController/getDictData', {dictCode: dictString}).then(res => {
      if (res.data.code == constants.resultSuccessCode &&
        res.data.result) {
        let dictData = res.data.result[constants.dict.优惠金额] || []
        let discountDefaultValue = 5
        dictData.forEach(item => {
          discountDefaultValue = item['itemValue'] || ''
        });
        this.setData({
          discountDefaultValue: discountDefaultValue,
        })
      }
    })
  },

  getParamInfo() {
    request.get('/HomeController/getDictData', {dictCode: getApp().globalData.paramDictCode}).then(res => {
      if (res.data.code == constants.resultSuccessCode
        && res.data.result) {

      }
    })
  },

  maxViewImg(e){
    let imgUrl=e.currentTarget.dataset.img
    wx.previewImage({
        current:imgUrl,
        urls: [imgUrl],
    })
  },

  onInput(e) {
    let name = e.currentTarget.dataset.name
    let value = e.detail.value
    if (name == 'declarationValue' && new Big(value).toNumber() > getApp().globalData.maxInsureValue) {
      value = getApp().globalData.maxInsureValue
    }
    this.setData({
      [`orderInfo.${name}`]: value
    })

    if (name == 'declarationValue') {//声明价值字段逻辑
      let calVaule = value
      if (calVaule) {
        if (calVaule > getApp().globalData.maxInsureValue) {
          calVaule = getApp().globalData.maxInsureValue
        }
        let insureValue = new Big(calVaule).times(new Big(this.data.insureRate))
        if (insureValue.toNumber() < 1) {
          insureValue = 1
        } else {
          insureValue = insureValue.round().toNumber()
        }
        this.setData({
          [`orderInfo.insureValue`]: insureValue
        })
      } else {
        this.setData({
          [`orderInfo.insureValue`]: ''
        })
      }
      
    }
    
  },

  onPayPicker(e) {
    let name = e.currentTarget.dataset.name
    if (name == 'payModeName') {
      this.setData({
        payModeVisible: true
      })
    } else if (name == 'isDiscountName') {
      this.setData({
        isDiscountVisible: true
      })
    }  else if (name == 'goodsTypeName') {
      this.setData({
        goodsTypeVisible: true
      })
    } else {
      this.setData({
        insureStatusVisible: true
      })
    }  
  },

  onColumnChange(e) {

  },

  onDiscountChange(e) {
    const { value } = e.detail;
    const { label } = e.detail;

    let discountValue = 0
    if (value[0] == 1) {
      discountValue = this.data.discountDefaultValue
    }
    console.log('discountValue:' + discountValue)
    this.setData({
      'orderInfo.discountValue': discountValue,
      isDiscount: value[0],
      isDiscountName: label[0],
      isDiscountVisible: false
    })
  },

  onPayChange(e) {
    const { value } = e.detail;
    const { label } = e.detail;

    this.setData({
      'orderInfo.payMode': value[0],
      payModeName: label[0],
      payModeVisible: false
    })
  },

  onGoodsChange(e) {
    const { value } = e.detail;
    const { label } = e.detail;

    this.setData({
      'orderInfo.goodsType': value[0],
      goodsTypeName: label[0],
      goodsTypeVisible: false
    })

    if (value[0] == '4') {
      this.setData({
        'isCal': true,
      })
    } else {
      this.setData({
        'isCal': false,
      })
    }
  },

  onInsureChange(e) {
    const { value } = e.detail;
    const { label } = e.detail;

    this.setData({
      'orderInfo.insureStatus': value[0],
      insureStatusName: label[0],
      insureStatusVisible: false
    })

    if (value[0] == '0') {
      this.setData({
        'orderInfo.declarationValue': '',
        'orderInfo.insureValue': ''
      })
    }
  },

  onPickerCancel(e) {
    this.setData({
      goodsTypeVisible: false,
      insureStatusVisible: false,
      payModeVisible: false,
      isDiscountVisible: false
    })
  },

  newaddress(e) {
    let key = e.currentTarget.dataset.key
    if (key) {
      getApp().globalData.pageData[constants.page_newaddress] = {prePage: key, isSave: false}
      wx.navigateTo({
        url: '/pages/address/newaddress/newaddress',
      })
    }
  },
  addressEdit(e) {
    let type = e.currentTarget.dataset.key
    if (type == '1') {
      let addressInfo = {}
      addressInfo.prePage = type
      addressInfo.isSave = false
      addressInfo.adressStationNo = this.data.orderInfo.startStation || ''
      addressInfo.adressStationName = this.data.orderInfo.startStationName || ''
      addressInfo.adressName = this.data.orderInfo.senderName || ''
      addressInfo.adressPhone = this.data.orderInfo.senderPhone || ''
      addressInfo.keyId = this.data.jiAddressId || ''

      getApp().globalData.pageData[constants.page_newaddress] = addressInfo
      wx.navigateTo({
        url: '/pages/address/newaddress/newaddress',
      })
    } else {
      let addressInfo = {}
      addressInfo.prePage = type
      addressInfo.isSave = false
      addressInfo.adressStationNo = this.data.orderInfo.endStation || ''
      addressInfo.adressStationName = this.data.orderInfo.endStationName || ''
      addressInfo.adressName = this.data.orderInfo.consigneeName || ''
      addressInfo.adressPhone = this.data.orderInfo.consigneePhone || ''
      addressInfo.keyId = this.data.shouAddressId || ''

      getApp().globalData.pageData[constants.page_newaddress] = addressInfo
      wx.navigateTo({
        url: '/pages/address/newaddress/newaddress',
      })
    }

  },
  addressbook(e) {
    let key = e.currentTarget.dataset.key
    if (key) {
      getApp().globalData.pageData[constants.page_addressbook] = {prePage: key}
      wx.navigateTo({
        url: '/pages/address/addressbook/addressbook',
      })
    }
    
  },
  orderCommit() {
    if (this.data.loading) {
      return false
    } else {
      this.setData({
        loading: true,
      })
    }
    if (this.data.isCal) {
      for (const key in this.data.requireList) {
        if (!this.data.orderInfo[key]) {
          wx.showToast({
            title: this.data.requireList[key],
            icon: 'error',
            duration: 2000
          })
          this.setData({
            loading: false,
          })
          return
        }
  
      }
    } else {
      for (const key in this.data.requireList) {
        if (!this.data.excludeList[key] && !this.data.orderInfo[key]) {
          wx.showToast({
            title: this.data.requireList[key],
            icon: 'error',
            duration: 2000
          })
          this.setData({
            loading: false,
          })
          return
        }
  
      }
    }
    
    let user = getApp().getUserInfo()
    let data = Object.assign({}, this.data.orderInfo, user)
    let that = this
    request.post('/UserController/savePackage', data).then(res => {
      if (res.data.code == constants.resultSuccessCode) {
        if (this.data.orderType == '1') {
          
          wx.showToast({
            title: '下单成功',
            icon: 'success',
            duration: 2000,
            success: res => {
              setTimeout(function() {
                wx.navigateBack()
              }, 2000)
            }
          })

        } else {
          getApp().globalData.pageData[constants.page_waiterprint] = res.data.result
          wx.showToast({
            title: '下单成功',
            icon: 'success',
            duration: 2000,
            success: res => {
              setTimeout(function() {
                wx.navigateTo({
                  url: '/pages/waiter/print/print',
                })
              }, 2000)
            }
          })
          
        }
      } else {
        wx.showToast({
          title: res.data.message || '下单失败',
          icon: 'error',
          duration: 2000
        })
        this.setData({
          loading: false,
        })
      }
    }).catch((err) => {
      this.setData({
        loading: false,
      })
    })
  },
  /**
   * 添加图片
   */
  addPhone(){
    const app = getApp();
    let that=this;
    let imgList = this.data.imgList
    wx.chooseImage({
        count: 1, // 可选择的图片数量
        sizeType: ['compressed'], // 压缩图片
        sourceType: ['album', 'camera'], // 来源：相册或相机
        success: (res) => {
            // 将选择的图片上传到服务器
            imgList.push(res.tempFilePaths[0])
            that.setData({
                imgList: imgList
            });
            wx.uploadFile({
                url: app.globalData.uploadServer, //后端接口
                filePath: res.tempFilePaths[0],
                name: 'file',
                header: "application/json",
                success(res) {
                    let data = JSON.parse(res.data)
                    if(data.code == "200"){
                        let goodsPhoto = ''
                        if (that.data.orderInfo.goodsPhoto) {
                          goodsPhoto = that.data.orderInfo.goodsPhoto+","+data.message
                        } else {
                          goodsPhoto = data.message
                        }

                        that.setData({
                            'orderInfo.goodsPhoto':goodsPhoto
                        });
                    }else{
                        wx.showToast({
                            title: res.data.message || '上传失败',
                            icon: 'error',
                            duration: 2000
                          })
                    }
                   
                },
                fail(e) {
                    console.log(e);
                }
            })
        },
        fail(e) {
            console.log(e+"上传失败");
        }
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    let address = getApp().globalData.pageData[constants.order_address]
    if (address && address['prePage']) {
      if (address['prePage'] == '1') {
        let jiAddressId = address.keyId || null
        this.setData({
          inputJi: false,
          jiAddressId: jiAddressId,
          'orderInfo.startStation': address['adressStationNo'] || '',
          'orderInfo.startStationName': address['adressStationName'] || '',
          'orderInfo.senderName': address['adressName'] || '',
          'orderInfo.senderPhone': address['adressPhone'] || '',
        })
      } else {
        let shouAddressId = address.keyId || null
        this.setData({
          inputShou: false,
          shouAddressId: shouAddressId,
          'orderInfo.endStation': address['adressStationNo'] || '',
          'orderInfo.endStationName': address['adressStationName'] || '',
          'orderInfo.consigneeName': address['adressName'] || '',
          'orderInfo.consigneePhone': address['adressPhone'] || '',
        })
      }
    }

    //处理优惠卷
    let couponData = getApp().globalData.pageData[constants.page_couponSelect]
    if (couponData && couponData.keyId) {
      this.setData({
        'orderInfo.couponId': couponData['keyId'] || '',
        'orderInfo.couponName': couponData['couponName'] || '',
      })
    }
  },

  onCouponClick(e) {
    wx.navigateTo({
      url: '/pages/mypage/couponSelect/couponSelect',
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})
